<?php
// +-------------------------------------------------------------------
// | 
// +-------------------------------------------------------------------
// | Copyright (c) 2009-2016 All rights reserved.
// +-------------------------------------------------------------------
namespace Kcdns\Admin\Model;
use Kcdns\User\Api\UserApi;

class MemberModel extends CommonModel
{

    /**
     * 格式化行操作按钮
     * 根据当前状态切换显示 启用/禁用按钮
     */
    protected function _formatListOpration ($row)
    {
        $opration = $this->cfg->listOpration;
        foreach ($opration as &$v)
        {
            if ($v['key'] == 'status')
            {
                $v['label'] = $row['member.status'] == 1 ? '禁用' : '启用';
                $v['url'] .= "&" . $this->cfg->escape("member.status") . "=" . ($row['member.status'] == 1 ? 0 : 1);
            }
            // 替换地址中的字段 : [action_log.id] -> action_log.id=1024
            $v['url'] = $this->_bindUrl($v['url'], $row);
        }
        return $opration;
    }

    /**
     * 新增用户
     */
    public function insert ($data)
    {
        $formData = $this->_getFormData($data);
        $memberData = $formData[$this->name];
        
        $memberData['password'] == $memberData['repassword'] or E('两次输入密码不一致！');
        
        /* 调用注册接口注册用户 */
        $User = new UserApi();
        $uid = $User->register($formData['ucenter_member']['username'], $memberData['password'], $memberData['email'] ?  : uniqid() . '@kcdns.com');
        
        if ($uid < 0)
        {
            $arr = array(
                    - 1 => '用户名长度必须在16个字符以内！',
                    - 2 => '用户名被禁止注册！',
                    - 3 => '用户名被占用！',
                    - 4 => '密码长度必须在6-30个字符之间！',
                    - 5 => '邮箱格式不正确！',
                    - 6 => '邮箱长度必须在1-32个字符之间！',
                    - 7 => '邮箱被禁止注册！',
                    - 8 => '邮箱被占用！',
                    - 9 => '手机格式不正确！',
                    - 10 => '手机被禁止注册！',
                    - 11 => '手机号被占用！'
            );
            E($arr[$uid] ?  : '未知错误');
        }
        
        // 注册成功
        $user = array(
                'uid' => $uid,
                'nickname' => $memberData['nickname'],
                'status' => 1,
                'cover_id' => $memberData['cover_id'] ?  : 0,
                'description' => $memberData['description'] ?  : '',
                'author_text' => $memberData['author_text'] ?  : '',
                'uuid' => guid(),
                'cate_auth' => $memberData['cate_auth'] ?  : ''
        );
        
        $this->data($user)->add() or E('添加失败');
        return true;
    }

    /**
     * 更新用户信息/密码
     */
    protected function _update ($formData = [], $fillData = [], $where = [])
    {
        $data = $formData[$this->name];
        if ($data['password'])
        {
            $data['password'] == $data['repassword'] or E('密码和重复密码不一致！');
            $res = M('ucenter_member')->where(array(
                    'id' => $data['uid']
            ))->save([
                    'password' => md5(sha1($data['password']) . C('DATA_AUTH_KEY'))
            ]);
            $res === false and E('更新密码失败');
        }
        return parent::_update($formData, $fillData);
    }

    /**
     * 不能更改超级管理员状态
     */
    protected function _set ($setOptions)
    {
        if (in_array(C('USER_ADMINISTRATOR'), $setOptions['where'][$this->getPk()][1]))
        {
            throw new \Exception('不能禁用开发者账号');
        }
        return parent::_set($setOptions);
    }

    protected function _del ($delOptions)
    {
        $status = parent::_del($delOptions);
        if ($status)
        {
            M('ucenter_member')->where([
                    'id' => $delOptions['where']['uid']
            ])->delete();
        }
        return $status;
    }

    /**
     * 修改密码
     */
    public function editPassword ($data = [])
    {
        $formData = $this->_getFormData($data);
        $data = $formData[$this->name];
        
        $data['password'] === $data['repassword'] or E('新密码与确认密码不一致');
        
        $res = (new UserApi())->updateInfo(UID, $data['old'], [
                'password' => $data['password']
        ]);
        $res['status'] or E($res['info']);
        
        $this->logout();
        return true;
    }

    /**
     * 获取用户已授权的组
     */
    public function getDataGroup ($idOrRow, $where = [])
    {
        $formOptions = $this->_getDataWhere($idOrRow, $where);
        $uid = $idOrRow['member.uid'];
        $user_groups = AuthGroupModel::getUserGroup($uid);
        $data['uid'] = $uid;
        foreach ($user_groups as $value)
        {
            $data['group_id'][] = $value['group_id'];
        }
        $data['member.group_id'] = implode(',', $data['group_id']);
        return $data;
    }

    /**
     * 更新用户已授权的组
     */
    public function updateGroup ($data, $fillData = [], $where = [])
    {
        $_REQUEST['batch'] = true;
        $formData = $this->_getFormData($data, $fillData);
        
        $uid = (int) $formData['member']['uid'] or E('参数有误');
        $gid = $formData['member']['group_id'];
        
        is_administrator($uid) and E('该用户为超级管理员');
        M('Member')->where(array(
                'uid' => $uid
        ))->find() or E('用户不存在');
        
        $AuthGroup = D('AuthGroup');
        
        $AuthGroup->addToGroup($uid, implode(',', $gid)) or E($AuthGroup->error ?  : '操作失败');
        return true;
    }
    
    // 登录指定用户
    public function login ($uid)
    {
        /* 检测是否在当前应用注册 */
        $user = $this->field(true)->find($uid);
        (! $user || 1 != $user['status']) and E('用户不存在或已被禁用！');
        
        /* 更新登录信息 */
        $data = [
                'uid' => $user['uid'],
                'login' => [
                        'exp',
                        '`login`+1'
                ],
                'last_login_time' => NOW_TIME,
                'last_login_ip' => get_client_ip(1)
        ];
        $this->save($data);
        
        /* 记录登录SESSION和COOKIES */
        $auth = [
                'uid' => $user['uid'],
                'username' => $user['nickname'],
                'last_login_time' => $user['last_login_time']
        ];
        
        action_log('user_login', 'member', $uid, $uid);
        session('user_auth', $auth);
        session('USER_AUTH_SIGN', data_auth_sign($auth));
        
        return true;
    }
    
    // 注销当前用户
    public function logout ()
    {
        session('user_auth', null);
        session('USER_AUTH_SIGN', null);
        session('[destroy]');
    }
}
